﻿using System;
using System.Text;
using System.Web.Mvc;
using XieCan.AspMVC.Extensions;

namespace XieCan.AspMVC.Web
{
    /// <summary>
    /// 继承JsonResut，重写序列化方式
    /// </summary>
    public class JsonNetResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");
            var response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrWhiteSpace(ContentType) ? "application/json" : ContentType;
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;
            var result = Data.ToJson();
            if (result.Success)
            {
                response.Write(result.Data);
            }
            //var scriptSerializer = JsonSerializer.Create(Settings);
            //using (var sw = new StringWriter())
            //{
            //    scriptSerializer.Serialize(sw, Data);
            //    response.Write(sw.ToString());
            //}
        }
    }

    public partial class BaseController : Controller
    {
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }
    }
}